package com.haiyuancloud.base.menu.controller;

import com.haiyuancloud.base.call.CallDealModel;
import com.haiyuancloud.base.call.CallDealService;
import com.haiyuancloud.common.core.entity.CurrentUser;
import com.haiyuancloud.common.core.entity.HaiyuanResponse;
import com.haiyuancloud.common.core.entity.constant.HaiyuanConstant;
import com.haiyuancloud.common.core.entity.constant.StringConstant;
import com.haiyuancloud.common.core.entity.router.VueRouter;
import com.haiyuancloud.common.core.entity.system.Menu;
import com.haiyuancloud.common.core.entity.system.TbOrgMenu;
import com.haiyuancloud.common.core.entity.system.TbOrgRoleMenu;
import com.haiyuancloud.common.core.utils.HaiyuanUtil;
import com.haiyuancloud.base.menu.mapper.TbOrgMenuMapper;
import com.haiyuancloud.base.menu.mapper.TbOrgRoleMenuMapper;
import com.haiyuancloud.base.menu.service.IMenuService;
import com.alibaba.fastjson.JSON;
import com.haiyuancloud.sys.chain.parser.plugin.RegisterSysDSChainPlugin;
import com.haiyuancloud.sys.chain.parser.plugin.SysPropChainPlugin;
import com.haiyuancloud.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.encoder.org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author haiyuan
 */
@Slf4j
@RestController
@RequestMapping
@RequiredArgsConstructor
public class MenuController {

    private final TbOrgRoleMenuMapper tbOrgRoleMenuMapper;

    private final TbOrgMenuMapper tbOrgMenuMapper;

    private final IMenuService menuService;

    @Resource
    private RegisterSysDSChainPlugin registerSysDSChainPlugin;

    @Resource
    private SysPropChainPlugin sysPropChainPlugin;

    @Resource
    private CallDealService callDealService;

    /**
     * 编译接口
     * @return
     */
    private List<Map<String,Object>> getCompilePageCntList(){
        CallDealModel callDealModel = new CallDealModel();
        callDealModel.setAccess_token(HaiyuanUtil.getCurrentTokenValue());
        callDealModel.setS_PAGE_NAME("(TB_UI_PAGE_COMPILE_LOG)首页编译页面统计接口");
        callDealModel.setS_PAGE_ID_IDX(7630042955864L);
        callDealModel.setS_PAGE_VER_IDX("v0.02");
        callDealModel.setI_PARTITION(32);
        Integer pageNo = 1;
        Integer pageSize = 10;
        Map<String,Object> submitData = new HashMap<>();
        String formatStyle = "yyyy-MM-dd HH:mm:ss+d+-1";
        submitData.put("D_START_CREATE_TIME",  ObjectUtil.getFormatDate(formatStyle));
        List<Map<String,Object>> callDealList = callDealService.getPageList(callDealModel,pageNo,pageSize,submitData);
        return callDealList;
    }

    /**
     * 核心接口
     * @return
     */
    private  Map<String,Object> getCoreData(){
        CallDealModel callDealModel = new CallDealModel();
        callDealModel.setAccess_token(HaiyuanUtil.getCurrentTokenValue());
        callDealModel.setS_PAGE_NAME("(TB_DEV_WORK_CORE_STAT_DD)首页按天查询工作成果接口");
        callDealModel.setS_PAGE_ID_IDX(	7629975847838L);
        callDealModel.setS_PAGE_VER_IDX("v0.02");
        callDealModel.setI_PARTITION(32);
        Integer pageNo = 1;
        Integer pageSize = 12;
        Map<String,Object> submitData = new HashMap<>();
        String formatStyle = "yyyyMMdd+d+-"+pageSize;
        submitData.put("I_START_STAT_CYCLE",  ObjectUtil.getFormatDate(formatStyle));
        List<Map<String,Object>> callDealList = callDealService.getPageList(callDealModel,pageNo,pageSize,submitData);
        List<Map<String,Object>> visitList =  new ArrayList<>();
        List<Map<String,Object>> compileList =  new ArrayList<>();
        List<Map<String,Object>> workList =  new ArrayList<>();
        for(Map<String,Object> callDeal : callDealList){
            Map<String,Object> visitData = new HashMap<>();
            visitData.put("days",ObjectUtil.toString(callDeal.get("I_STAT_CYCLE")));
            visitData.put("count",callDeal.get("I_VISIT_CNT"));
            visitList.add(visitData);

            Map<String,Object> compileData = new HashMap<>();
            compileData.put("days",ObjectUtil.toString(callDeal.get("I_STAT_CYCLE")));
            compileData.put("count",callDeal.get("I_COMPILE_CNT"));
            compileList.add(compileData);

            Map<String,Object> workData = new HashMap<>();
            workData.put("days",ObjectUtil.toString(callDeal.get("I_STAT_CYCLE")));
            workData.put("count",callDeal.get("I_WORK_CNT"));
            workList.add(workData);
        }

        Map<String,Object> statData = new HashMap<>();
        statData.put("visitList",visitList);
        statData.put("compileList",compileList);
        statData.put("workList",workList);
        return statData;
    }

    /**
     * 查询本月累计工作
     * @return
     */
    private  Map<String,Object> getCoreDataMM(){
        CallDealModel callDealModel = new CallDealModel();
        callDealModel.setAccess_token(HaiyuanUtil.getCurrentTokenValue());
        callDealModel.setS_PAGE_NAME("(TB_DEV_WORK_CORE_STAT_MM)数据分页");
        callDealModel.setS_PAGE_ID_IDX(	42365356081939L);
        callDealModel.setS_PAGE_VER_IDX("v0.02");
        callDealModel.setI_PARTITION(32);
        Integer pageNo = 1;
        Integer pageSize = 1;
        Map<String,Object> submitData = new HashMap<>();
        String formatStyle = "yyyyMM";
        submitData.put("I_STAT_CYCLE",  ObjectUtil.getFormatDate(formatStyle));
        List<Map<String,Object>> callDealList = callDealService.getPageList(callDealModel,pageNo,pageSize,submitData);
        Map<String,Object> callDeal = new HashMap<>();
        if(ObjectUtil.isNotNull(callDealList)){
            Map<String,Object> callTmpDeal = callDealList.get(0);
            callDeal.put("I_TBL_CNT",callTmpDeal.get("I_TBL_CNT"));
            callDeal.put("I_MAGIC_CNT",callTmpDeal.get("I_MAGIC_CNT"));
            callDeal.put("I_DEAL_CNT",callTmpDeal.get("I_DEAL_CNT"));
            callDeal.put("I_UI_CNT",callTmpDeal.get("I_UI_CNT"));
        }else{
            callDeal.put("I_TBL_CNT",0);
            callDeal.put("I_MAGIC_CNT",0);
            callDeal.put("I_DEAL_CNT",0);
            callDeal.put("I_UI_CNT",0);
        }

        Map<String,Object> statData = new HashMap<>();
        statData.put("coreDataMM",callDeal);
        return statData;
    }

    @GetMapping("/index")
    public HaiyuanResponse index() {
        Map<String, Object> data = new HashMap<>(5);
        data.put("compilePageList",getCompilePageCntList());
        data.putAll(getCoreData());
        data.putAll(getCoreDataMM());
        return new HaiyuanResponse().data(data);
    }
    /**
     * 当前用户路由
     */
    @ResponseBody
    @GetMapping("/listAuthResource/{sys}")
    public HaiyuanResponse listAuthResource(@PathVariable String sys, HttpServletRequest request) {

        Long defProductId = ObjectUtil.toLong(HaiyuanConstant.S_PRODUCT_ID);
        Long productId = ObjectUtil.toLong(request.getParameter("productId"),defProductId);
        CurrentUser currentUser = HaiyuanUtil.getCurrentUser();
        registerSysDSChainPlugin.push(currentUser.getOrgDsId());
        Map<String, Object> result = new HashMap<>(5);
        List<TbOrgMenu> tbOrgMenuDistinctList = this.findMenuListById(sys,productId);
        List<VueRouter<Menu>> userRouters = menuService.getUserRouters(tbOrgMenuDistinctList);
        result.put("routes", userRouters);
        result.put("permissions", this.getPermissions(tbOrgMenuDistinctList));

        return new HaiyuanResponse().data(result);
    }

    private  List<TbOrgMenu> findMenuListById(String sys,Long productId){
        List<TbOrgRoleMenu> tbOrgRoleMenuList = new ArrayList<>();
        String orgRoleIdId = HaiyuanUtil.getCurrentUser().getRoleIds();
        if(ObjectUtil.isNotNull(orgRoleIdId)) {
            List<Long> roleIdList = Arrays.asList(orgRoleIdId.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            for (Long iRoleId : roleIdList) {
                List<TbOrgRoleMenu> tbOrgMenuTempList = tbOrgRoleMenuMapper.findMenuListByRolefId(iRoleId);
                tbOrgRoleMenuList.addAll(tbOrgMenuTempList);
            }
        }


        List<TbOrgMenu> tbOrgMenuList = new ArrayList<>();
        if(null == tbOrgRoleMenuList || tbOrgRoleMenuList.size() == 0){
            CurrentUser currentUser = HaiyuanUtil.getCurrentUser();
            String adminAcc = sysPropChainPlugin.getStrProp("S_SYS_ADMIN_ACC","v0.02","admin");
            if(adminAcc.equals(currentUser.getUserAcc()) || currentUser.getUserAcc().equals(currentUser.getTenantAcc())){
                log.error("超级管理员登录#"+adminAcc);
                registerSysDSChainPlugin.push(currentUser.getOrgDsId());
                List<TbOrgMenu> tbOrgMenuAllList = tbOrgMenuMapper.findMenuList();
                tbOrgMenuList.addAll(tbOrgMenuAllList);
            }
        }else {
            for (TbOrgRoleMenu tbOrgRoleMenu : tbOrgRoleMenuList) {
                List<TbOrgMenu> tbOrgMenuTempList = this.getOrgMenuBySysId(sys, tbOrgRoleMenu.getIMenuId());
                if (ObjectUtils.isNotEmpty(tbOrgMenuTempList)) {
                    tbOrgMenuList.addAll(tbOrgMenuTempList);
                }
            }
        }
        List<String> pathIdList = menuService.getPathIdList(tbOrgMenuList);
        Map<String,String> idData = menuService.getIdData(tbOrgMenuList);

        pathIdList.forEach(id ->{
            if(!idData.containsKey(id) && StringUtils.isNotBlank(id)){
                List<TbOrgMenu> tbOrgMenuTempList = tbOrgMenuMapper.findMenuListById(id);
                if(ObjectUtils.isNotEmpty(tbOrgMenuTempList)) {
                    tbOrgMenuList.addAll(tbOrgMenuTempList);
                }
            }
        });
        if(ObjectUtil.isNotNull(productId)) {
            List<TbOrgMenu> tbOrgMenuDistinctList = tbOrgMenuList.stream().filter(orgMenu -> productId.equals(orgMenu.getSProductId())).distinct().collect(Collectors.toList());
            tbOrgMenuList.clear();
            return tbOrgMenuDistinctList;
        }else {
            List<TbOrgMenu> tbOrgMenuDistinctList =tbOrgMenuList.stream().distinct().collect(Collectors.toList());
            return tbOrgMenuDistinctList;
        }
    }

    private String[] getPermissions(List<TbOrgMenu> tbOrgMenuList){
        String userPermissions = tbOrgMenuList.stream().map(TbOrgMenu::getSAuthCode).filter(s -> !("".equals(s) || null == s)).collect(Collectors.joining(StringConstant.COMMA));
        String[] permissionArray = new String[0];
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(userPermissions)) {
            permissionArray = StringUtils.splitByWholeSeparatorPreserveAllTokens(userPermissions, StringConstant.COMMA);
        }
        return permissionArray;
    }

    private List<TbOrgMenu> getOrgMenuBySysId(String sys,Long iMenuId){
        List<TbOrgMenu> tbOrgMenuList = new ArrayList<>();
        List<TbOrgMenu> tbOrgMenuTempList = tbOrgMenuMapper.findMenuListByMenuId(iMenuId);
        if(null != tbOrgMenuTempList ) {
            if(StringUtils.isBlank(sys)) {
                tbOrgMenuList.addAll(tbOrgMenuTempList);
            }else{
                List<String> sysIdList  = Arrays.asList(sys,",");
                tbOrgMenuTempList.forEach(tbOrgMenu ->{
                    String iMenuSys = Long.toString(tbOrgMenu.getIMenuSys());
                    sysIdList.forEach(id ->{
                        if(StringUtils.isNotBlank(id) && id.equals(iMenuSys) ){
                            tbOrgMenuList.add(tbOrgMenu);
                        }
                    });
                } );
            }
        }
        return tbOrgMenuList;
    }
}
